#####################
### Load Packages ###
#####################

library(haven)


# Set this Working Directory to the Folder with the Replication Files
#setwd("C:/Steven/GDrive/Research Files/Clark-Rogers/Descriptive Representation/APSR Final Submission/Replication")

###
# Functions
###

# Function to Clean Up STATA Estimates and Confidence Intervals
  CleanUp <- function(CurrentVariable)
    {
      CurrentVariable <- gsub("=","", CurrentVariable)
      CurrentVariable <- gsub("[/*]","", CurrentVariable)
      CurrentVariable <- gsub("\\(","", CurrentVariable)
      CurrentVariable <- gsub("\\)","", CurrentVariable)
      CurrentVariable <- gsub("\\]","", CurrentVariable)
      CurrentVariable <- gsub("\\[","", CurrentVariable)
      CurrentVariable <- as.numeric(CurrentVariable)
      return(CurrentVariable)
    }

  
# Function to Extract and Clean Estimate and Confidence Interval
  
  ExtractEstimates <- function(CurrentLabel, CurrentEstimate, CurrentCI)
    {
    
    LowerBound <- sapply(strsplit(CurrentCI, ","), "[", 1)
    UpperBound <- sapply(strsplit(CurrentCI, ","), "[", 2)
    
    CurrentEstimates <- data.frame(matrix(NA, 1,0))
      CurrentEstimates$Label <- CurrentLabel
      CurrentEstimates$Coefficient <- CleanUp(CurrentEstimate)
      CurrentEstimates$LowerBound <-  CleanUp(LowerBound)
      CurrentEstimates$UpperBound <-  CleanUp(UpperBound)
    
    return(CurrentEstimates)
    }

# Function to Create Base Plot
  BasePlot <- function(CurrentCoefficient, CurrentYLocation)
  {
    plot(RogersEstimates$Coefficient, RogersEstimates$YLocation,
         type="n",
         ylab=" ",
         xaxt="n",
         yaxt="n",
         cex.main=1.3,
         xlim=c(-.032,.032),
         ylim=c(0,3),
         cex.axis=.7,
         xaxs = "i", # Removes Inner Margin
         yaxs = "i", # Removes Inner Margin
         #main="Probabilities of Incumbents Being Contested by Party Membership",
         xlab=" ",
         family="B"
    )
    abline(v=0, col="grey", lty=2)
    
    # Make the ticks on the line
    axis(side=1, at=c(-0.03,-0.02, -0.01, 0, 0.01, 0.02,0.03), labels=c("","", "", "", "", "",""))
    
    # Put the numbers higher than R wants with ticks
    axis(side=1, at=c(-0.03,-0.02, -0.01, 0, 0.01, 0.02,0.03), labels=c("-0.03","-0.02", "-0.01", "0", "0.01", "0.02","0.03"), line=-.5, tick="FALSE", cex.axis=.75)
    
    
  }

# Function to Create Completely Blank Plot
  BlankPlot <- function(CurrentEstimates)
  {
    plot(CurrentEstimates$Coefficient, CurrentEstimates$YLocation,
         type="n",
         ylab=" ",
         xaxt="n",
         yaxt="n",
         cex.main=1.3,
         xlim=c(-.032,.032),
         ylim=c(0,3),
         cex.axis=.9,
         xaxs = "i", # Removes Inner Margin
         yaxs = "i", # Removes Inner Margin
         #main="Probabilities of Incumbents Being Contested by Party Membership",
         xlab=" ",
         family="B",
         bty="n"
    )
  }
  


##
# Rogers Estimates
##
    ###
    # Women
    ###
      
      # Women Congress - Belief
      
      RogersCongressRaw <- read.csv("Scripts/Figures/Estimates/Clark-Rogers-Congress-Women-Trust.csv")
      colnames(RogersCongressRaw) <- c("VariableName", "Estimates")
      
      # Determine the Rows of the Coefficient and Standard Error
      RogersCongressRaw$RowNumber <- rownames(RogersCongressRaw)
      EstimateRowNumber <- as.numeric(RogersCongressRaw$RowNumber[RogersCongressRaw$VariableName=="=Belief_WomenCongress"])
      RogersCongress_BeliefEstimate <- RogersCongressRaw$Estimates[EstimateRowNumber]
      RogersCongress_ConfidenceInterval <- RogersCongressRaw$Estimates[EstimateRowNumber+1]
      
      RogersEstimates <- ExtractEstimates("Rogers - Congress - Women - Belief", RogersCongress_BeliefEstimate, RogersCongress_ConfidenceInterval)
      
      # Women State Leg 
      
      RogersStateLegRaw <- read.csv("Scripts/Figures/Estimates/Clark-Rogers-StateLeg-Women-Trust.csv")
      colnames(RogersStateLegRaw) <- c("VariableName", "Estimates")

      
      # Factual Estimates
        RogersStateLegRaw$RowNumber <- rownames(RogersStateLegRaw)
        FactualEstimateRowNumber <- as.numeric(RogersStateLegRaw$RowNumber[RogersStateLegRaw$VariableName=="=True_WomenStateLeg"])
        RogersStateLeg_FactualEstimate <- RogersStateLegRaw$Estimates[FactualEstimateRowNumber]
        RogersStateLeg_FactualConfidenceInterval <- RogersStateLegRaw$Estimates[FactualEstimateRowNumber+1]
      
      CurrentEstimates <- ExtractEstimates("Rogers - StateLeg - Women - Factual", RogersStateLeg_FactualEstimate, RogersStateLeg_FactualConfidenceInterval)
      RogersEstimates <- rbind(RogersEstimates, CurrentEstimates)
      
      # Belief Estimates
        RogersStateLegRaw$RowNumber <- rownames(RogersStateLegRaw)
        BeliefEstimateRowNumber <- as.numeric(RogersStateLegRaw$RowNumber[RogersStateLegRaw$VariableName=="=Belief_WomenStateLeg"])
        RogersStateLeg_BeliefEstimate <- RogersStateLegRaw$Estimates[BeliefEstimateRowNumber]
        RogersStateLeg_BeliefConfidenceInterval <- RogersStateLegRaw$Estimates[BeliefEstimateRowNumber+1]
      
      CurrentEstimates <- ExtractEstimates("Rogers - StateLeg - Women - Belief", RogersStateLeg_BeliefEstimate, RogersStateLeg_BeliefConfidenceInterval)
      RogersEstimates <- rbind(RogersEstimates, CurrentEstimates)  
    
    ###
    # Blacks
    ###
      
      # Blacks Congress - Belief
      
      RogersCongressRaw <- read.csv("Scripts/Figures/Estimates/Clark-Rogers-Congress-Blacks-Trust.csv")
      colnames(RogersCongressRaw) <- c("VariableName", "Estimates")
      
      # Determine the Rows of the Coefficient and Standard Error
      RogersCongressRaw$RowNumber <- rownames(RogersCongressRaw)
      EstimateRowNumber <- as.numeric(RogersCongressRaw$RowNumber[RogersCongressRaw$VariableName=="=Belief_BlackCongress"])
      RogersCongress_BeliefEstimate <- RogersCongressRaw$Estimates[EstimateRowNumber]
      RogersCongress_ConfidenceInterval <- RogersCongressRaw$Estimates[EstimateRowNumber+1]
      
      CurrentEstimates <- ExtractEstimates("Rogers - Congress - Blacks - Belief", RogersCongress_BeliefEstimate, RogersCongress_ConfidenceInterval)
      RogersEstimates <- rbind(RogersEstimates, CurrentEstimates)  
      
      # Blacks State Leg
      
      RogersStateLegRaw <- read.csv("Scripts/Figures/Estimates/Clark-Rogers-StateLeg-Blacks-Trust.csv")
      colnames(RogersStateLegRaw) <- c("VariableName", "Estimates")
      
      # Factual Estimates
      RogersStateLegRaw$RowNumber <- rownames(RogersStateLegRaw)
      FactualEstimateRowNumber <- as.numeric(RogersStateLegRaw$RowNumber[RogersStateLegRaw$VariableName=="=True_BlackStateLeg"])
      RogersStateLeg_FactualEstimate <- RogersStateLegRaw$Estimates[FactualEstimateRowNumber]
      RogersStateLeg_FactualConfidenceInterval <- RogersStateLegRaw$Estimates[FactualEstimateRowNumber+1]
      
      CurrentEstimates <- ExtractEstimates("Rogers - StateLeg - Blacks - Factual", RogersStateLeg_FactualEstimate, RogersStateLeg_FactualConfidenceInterval)
      RogersEstimates <- rbind(RogersEstimates, CurrentEstimates)
      
      # Belief Estimates
      RogersStateLegRaw$RowNumber <- rownames(RogersStateLegRaw)
      BeliefEstimateRowNumber <- as.numeric(RogersStateLegRaw$RowNumber[RogersStateLegRaw$VariableName=="=Belief_BlackStateLeg"])
      RogersStateLeg_BeliefEstimate <- RogersStateLegRaw$Estimates[BeliefEstimateRowNumber]
      RogersStateLeg_BeliefConfidenceInterval <- RogersStateLegRaw$Estimates[BeliefEstimateRowNumber+1]
      
      CurrentEstimates <- ExtractEstimates("Rogers - StateLeg - Blacks - Belief", RogersStateLeg_BeliefEstimate, RogersStateLeg_BeliefConfidenceInterval)
      RogersEstimates <- rbind(RogersEstimates, CurrentEstimates)  
      
      RogersEstimates$YLocation <- 1
      
      
###
# Plot Time
###
      
      
tiff(filename = "Figures/Figure-4.tiff", width = 7, height = 1.5, units = "in", pointsize = 12, res=1000)

           
      # Ultimately Going to Create Plot that is 2 rows by 4 Columns
      
      windowsFonts(
        A=windowsFont("Arial Black"),
        B=windowsFont("Cambria"),
        C=windowsFont("Comic Sans MS"),
        D=windowsFont("Symbol")
      )
      

      #par(family="B",
      #    mai=c(.5,.1,.1,.1), 
      #    mfrow=c(3,5))

      par(family="B",
          mai=c(.1,.1,.1,.1),
          mar=c(1.5,1,.9,1))
      
      nf <- layout(
        matrix(c(1,2,3,4,5,6,7,8,9,10), ncol=5, byrow=TRUE), 
        widths=c(1.5,1.5,1.5,1.5,1.5), 
        heights=c(3,3)
      )
      
##
# First Row of Beliefs
##
      
      # Label Plot
      
      BlankPlot(RogersEstimates)      
      
      text(-.004, 2.75, "Coefficients for Perceptions of", cex=.7)
      text(-.004, 2.1, "Descriptive Representation", cex=.7)
      
      legend(-.032,1.75, ncol=1,
             c("Current Study Estimates"),
             pch=c(2), lwd=c(1), col=c("black"),
             cex=.7, bty="n")    
          
      # Women in Congress Plot ~ Belief Only
          BasePlot(RogersEstimates$Coefficient, RogersEstimates$YLocation)

          title(main = "Women in Congress", cex.main = .9)
          
        # Stauffer
          #CurrentEstimates <- subset(RogersEstimates, RogersEstimates$Label=="Stauffer - Congress - Women - Belief")
          #segments(CurrentEstimates$LowerBound, CurrentEstimates$YLocation, CurrentEstimates$UpperBound, CurrentEstimates$YLocation)
          #points(CurrentEstimates$Coefficient, CurrentEstimates$YLocation, pch=1, cex=.75)
          
          
        # Rogers
          CurrentEstimates <- subset(RogersEstimates, RogersEstimates$Label=="Rogers - Congress - Women - Belief")
          segments(CurrentEstimates$LowerBound, CurrentEstimates$YLocation, CurrentEstimates$UpperBound, CurrentEstimates$YLocation)
          points(CurrentEstimates$Coefficient, CurrentEstimates$YLocation, pch=2, cex=.75)
            
      # Women in State Leg Plot - Belief Only
          BasePlot(RogersEstimates$Coefficient, RogersEstimates$YLocation)
          
          title(main = "Women in State Leg.", cex.main = .9)
          
          
          # Stauffer
              #CurrentEstimates <- subset(RogersEstimates, RogersEstimates$Label=="Stauffer - StateLeg - Women - Belief")
              #segments(CurrentEstimates$LowerBound, CurrentEstimates$YLocation, CurrentEstimates$UpperBound, CurrentEstimates$YLocation)
              #points(CurrentEstimates$Coefficient, CurrentEstimates$YLocation, pch=1, cex=.75)
              
          # Rogers
              CurrentEstimates <- subset(RogersEstimates, RogersEstimates$Label=="Rogers - StateLeg - Women - Belief")
              segments(CurrentEstimates$LowerBound, CurrentEstimates$YLocation, CurrentEstimates$UpperBound, CurrentEstimates$YLocation)
              points(CurrentEstimates$Coefficient, CurrentEstimates$YLocation, pch=2, cex=.75)
              
        # Blacks in Congress Plot ~ Belief Only
              BasePlot(RogersEstimates$Coefficient, RogersEstimates$YLocation)
              title(main = "Blacks in Congress", cex.main = .9)
              
              # Rogers
              CurrentEstimates <- subset(RogersEstimates, RogersEstimates$Label=="Rogers - Congress - Blacks - Belief")
              segments(CurrentEstimates$LowerBound, CurrentEstimates$YLocation, CurrentEstimates$UpperBound, CurrentEstimates$YLocation)
              points(CurrentEstimates$Coefficient, CurrentEstimates$YLocation, pch=2, cex=.75)
              
        # Blacks in State Leg Plot ~ Belief Only
              BasePlot(RogersEstimates$Coefficient, RogersEstimates$YLocation)
              title(main = "Blacks in State Leg.", cex.main = .9)
              
              # Rogers
              CurrentEstimates <- subset(RogersEstimates, RogersEstimates$Label=="Rogers - StateLeg - Blacks - Belief")
              segments(CurrentEstimates$LowerBound, CurrentEstimates$YLocation, CurrentEstimates$UpperBound, CurrentEstimates$YLocation)
              points(CurrentEstimates$Coefficient, CurrentEstimates$YLocation, pch=2, cex=.75)
              
##
# Second Row of Factual
##
        # Label Plot
            BlankPlot(RogersEstimates)      
            
            text(-.004, 2.75, "Coefficients for Actual", cex=.7)
            text(-.004, 2.1, "Descriptive Representation", cex=.7)

            legend(-.032,1.75, ncol=1,
                   c("Current Study Estimates"),
                   pch=c(2), lwd=c(1), col=c("black"),
                   cex=.7, bty="n")    
            
        # Women in Congress Plot ~ Factual Only
            BlankPlot(RogersEstimates)      
            

        
        # Women in State Leg Plot - Factual Only
              BasePlot(RogersEstimates$Coefficient, RogersEstimates$YLocation)
              
              # Stauffer
              #CurrentEstimates <- subset(RogersEstimates, RogersEstimates$Label=="Stauffer - StateLeg - Women - Factual")
              #segments(CurrentEstimates$LowerBound, CurrentEstimates$YLocation, CurrentEstimates$UpperBound, CurrentEstimates$YLocation)
              #points(CurrentEstimates$Coefficient, CurrentEstimates$YLocation, pch=1, cex=.75)
              
              # Rogers
              CurrentEstimates <- subset(RogersEstimates, RogersEstimates$Label=="Rogers - StateLeg - Women - Factual")
              segments(CurrentEstimates$LowerBound, CurrentEstimates$YLocation, CurrentEstimates$UpperBound, CurrentEstimates$YLocation)
              points(CurrentEstimates$Coefficient, CurrentEstimates$YLocation, pch=2, cex=.75)
              
        # Blacks in Congress Plot ~ Factual Only
              BlankPlot(RogersEstimates)      
              
        # Blacks in State Leg Plot ~ Belief Only
              BasePlot(RogersEstimates)
              
              # Rogers
              CurrentEstimates <- subset(RogersEstimates, RogersEstimates$Label=="Rogers - StateLeg - Blacks - Factual")
              segments(CurrentEstimates$LowerBound, CurrentEstimates$YLocation, CurrentEstimates$UpperBound, CurrentEstimates$YLocation)
              points(CurrentEstimates$Coefficient, CurrentEstimates$YLocation, pch=2, cex=.75)
              
      dev.off()        
              
              